package com.devshephard.jucks.CompleteFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class Test {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

      Test.test2();

    }

    /**
     * 没有返回值的Future异步回调任务
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void test1() throws ExecutionException, InterruptedException {
        CompletableFuture<Void> completableFuture =  CompletableFuture.runAsync(()->{
            try {
                Thread.sleep(2000); //这里会先执行主线程，等待completeFuture完成后再往下执行
                System.out.println("completeFuture执行完成！");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println(Thread.currentThread().getName() + " main线程运行");

        completableFuture.get();

    }

    /**
     * 有返回值的Future异步回调任务
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void test2() throws ExecutionException, InterruptedException {
        //使用消费型接口
        CompletableFuture<Integer> completableFuture =  CompletableFuture.supplyAsync(()->{
            System.out.println("completeFuture执行完成 ha！");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //int res = 10/0;
            return 1024;
        });


        completableFuture.whenComplete((t,u)->{
            System.out.println("t => " + t);
            System.out.println("u => " + u);
        }).exceptionally((e) ->{
            e.printStackTrace();
            System.out.println(e.getMessage());
            return 233;
        });

        System.out.println(Thread.currentThread().getName());
        TimeUnit.SECONDS.sleep(5);
    }
}
